package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 *
 * @author 12548
 * @date 2022/09/23
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取登录用户
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId != null) {
            //后端已登录,放行
            BaseContext.setCurrentId(empId);
            return true;
        }

        Long userId=(Long) request.getSession().getAttribute("user");
        if (userId!=null){
            //用户端已登录,放行
            BaseContext.setCurrentId(userId);
            return true;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        //没有登录,则不放行
        return false;

    }

}
